<?php

class CsvOutput implements RegistryObject, ReportOutput {

	public function setup() {
	}

	public function getTitle() {
		return "csv";
	}

	public function write($reportObj, $outputfile = null) {

		$reportTitle = $reportObj->getTitle();


		//Report title
		$output = nl("#".$reportTitle);


		$dom = $reportObj->getDOM();
		$qresults = $dom->getElementsByTagName("query-result");
		for ($i=0; $i<$qresults->length; $i++) {
			$qresult 	= $qresults->item($i);
			$qresultTitle 	= $qresult->getAttribute("title");
			$graph 		= $qresult->getAttribute("graph");

			//Query result title
			$output .= nl("#".$qresultTitle);
			$output .= nl("#".$graph);

			$dataRows = $qresult->getElementsByTagName("row");
			for ($d=0; $d<$dataRows->length; $d++) {

				$col = 0;

				$values = $dataRows->item($d)->getElementsByTagName("label");
				for ($p=0; $p<$values->length; $p++) {
					if ($col>0)
						$output .= ",";
					$output .= trim($values->item($p)->firstChild->nodeValue);
					$col++;
				}

				$values = $dataRows->item($d)->getElementsByTagName("p");
				for ($p=0; $p<$values->length; $p++) {
					if ($col>0)
						$output .= ",";
					$output .= trim($values->item($p)->firstChild->nodeValue);
					$col++;
				}

				$output .= nl("");
			}

			$output .= nl("");
		}

		header("Content-Type: text/plain");
		echo $output;
	}

}

Registry::register("output", new CsvOutput());

?>